<?php

namespace app\manystore\controller\my;

use app\common\controller\ManystoreBase;
use app\common\library\Sms as Smslib;
use fast\Random;
use think\Config;
use think\Validate;
use think\Hook;

use think\Db;
use app\manystore\Model\ManystoreModel;
use app\manystore\Model\User;

/**
 * 短信接口
 */
class ManyStoreSms extends ManystoreBase
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 发送短信验证码
     *
     * @ApiMethod (GET)
     * @ApiTitle    发送短信验证码

     * @ApiParams (name="event", type="string", required=false, description="短信类型,修改登陆密码=manystore_resetpwd")

     * @ApiSector   设置接口
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657984618",
          "data": null
        })
     */
    public function sendMsm()
    {
        $auth_type = ['manystore_resetpwd'];
        $event = $this->request->param('event');

        $user = $this->auth->getUserinfo();

        $mobile = $user['mobile'];
        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('未绑定手机号'));
        }

        $last = Smslib::get($mobile, $event);
        if ($last && time() - $last['createtime'] < 60) {
            $this->error(__('发送频繁'));
        }
        $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
        if ($ipSendTotal >= 5) {
            $this->error(__('发送频繁'));
        }
        
        if (!Hook::get('sms_send')) {
            $this->error(__('请在后台插件管理安装短信验证插件'));
        }

        $ret = Smslib::send($mobile, null, $event);
        if ($ret) {
            $this->success(__('发送成功'));
        } else {
            $this->error(__('发送失败，请检查短信配置是否正确'));
        }
    }
}